package actions;

/**
 * 通常对于逻辑上是一组的业务操作，我们可以用一个DispatchAction类来处理这些操作，这样可以减少
 * Action类的数量并且可以公用某些代码（如检验）， 对于使用FormBean的Action来说这种方式有一个限制，就是“复用”的一组操作FormBean
 * 必须相同，因此 不建议采用DispatchAction，我们主张不用FormBean的Action采用这种方式减少Action的数量
 * 如域对象的列表(list)、删除、详细信息显示等操作可以用一个DispatchAction来实现，
 * 只要实现方法listXXX(...)、deleteXXX(...)、displayXXX()、displayXXXForUpdate（）等即可，
 * 更详细的使用说明请查询Struts文档
 */
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.validator.DynaValidatorForm;

import service.UserAccountService;
import domain.UserAccount;

/**
 * 用户账号的主要的Action对象，用于显示列表、显示账号详细信息、删除用户帐号业务操作.
 * @author zhuweiguo
 */
public class UserAccountMainAction extends DispatchAction {
    /**
     * 用于操作用户帐号.
     */
    private UserAccountService userAccountService = null;

    /**
     * 显示所有用户帐号.
     * @param mapping struts mapping
     * @param form struts form
     * @param request http request
     * @param response http response
     * @return action forward
     * @throws Exception any execption
     */
    public ActionForward displayUserAccountMainScreen(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        // 调用UserAccountService取得账号列表
        Collection<UserAccount> result = userAccountService.getUserAccounts();
        // ���б����request��
        request.setAttribute("USER_ACCOUNT_LIST", result);
        return mapping.findForward("UserAccountMain.screen");
    }

    /**
     * 显示输入界面.
     * @param mapping struts mapping
     * @param form struts form
     * @param request http request
     * @param response http response
     * @return action forward
     * @throws Exception any execption
     */
    public ActionForward displayUserAccountCreateScreen(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        // 产生并保存Token,防止重复提交
        saveToken(request);
        // 初始化输入框
        DynaValidatorForm userAccountForm = (DynaValidatorForm) mapping
                .getModuleConfig().findFormBeanConfig("userAccountForm")
                .createActionForm(servlet);
        userAccountForm.set("userID", "yourAccount");
        userAccountForm.set("userName", "your name");
        userAccountForm.set("roleID", null);
        userAccountForm.set("password", "111111");

        // 将Struts form 设置到request中
        request.setAttribute("userAccountForm", userAccountForm);
        return mapping.findForward("UserAccountCreate.screen");

    }

    /**
     * 显示用户帐号详细信息用于更新操作.
     * @param mapping struts mapping
     * @param form struts form
     * @param request http request
     * @param response http response
     * @return action forward
     * @throws Exception any execption
     */
    public ActionForward displayUserAccountUpdateScreen(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        String userID = request.getParameter("userID");
        UserAccount userAccount = userAccountService
                .getUserAccountByUserid(userID);
        if (userAccount == null) {
            ActionMessages errMsgs = new ActionMessages();
            errMsgs.add("", new ActionMessage("errors.noSuchAccount"));
            this.saveErrors(request, errMsgs);
            return mapping.findForward("error.back");
        } else {
            /** 将需要修改的帐户信息字段填充form* */
            DynaValidatorForm userAccountForm = (DynaValidatorForm) mapping
                    .getModuleConfig().findFormBeanConfig("userAccountForm")
                    .createActionForm(servlet);
            userAccountForm.set("userID", userAccount.getUserID());
            userAccountForm.set("userName", userAccount.getUserName());
            userAccountForm.set("roleID", userAccount.getRoleID());
            userAccountForm.set("password", userAccount.getPassword());

            // 将Struts form 设置到request中
            request.setAttribute("userAccountForm", userAccountForm);
            // 设置token 防止重复提交
            this.saveToken(request);
            return mapping.findForward("UserAccountUpdate.screen");
        }
    }

    /**
     * 删除指定的用户帐号.
     * @param mapping struts mapping
     * @param form struts form
     * @param request http request
     * @param response http response
     * @return action forward
     * @throws Exception any execption
     */
    public ActionForward deleteUserAccount(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        String userID = request.getParameter("userID");
        UserAccount curUser = (UserAccount) request.getSession().getAttribute(
                "HUAXIA_CURRENT_USER");
        if (curUser.getUserID().equals(userID)) {
            ActionMessages errMsgs = new ActionMessages();
            errMsgs.add("", new ActionMessage("errors.deleteSelfAccount"));
            this.saveErrors(request, errMsgs);
            return mapping.findForward("error.back");
        }
        // 调用UserAccountService删除用户帐号
        userAccountService.deleteUserAccount(userID);
        return mapping.findForward("self");
    }

    /**
     * 将用户帐号列表导出到Excel文件中.
     * @param mapping struts mapping
     * @param form struts form
     * @param request http request
     * @param response http response
     * @return action forward
     * @throws Exception any execption
     */

    public ActionForward exportUserAccountsToExcel(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        Collection<UserAccount> pUserList = userAccountService
                .getUserAccounts();
        String templateFileName = Thread.currentThread()
                .getContextClassLoader()
                .getResource("userAccount-template.xls").getFile();
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("useracounts", pUserList);
        request.setAttribute(CommonExcelExportAction.EXCEL_TEMPLATE_NAME,
                templateFileName);
        request.setAttribute(CommonExcelExportAction.EXCEL_FILE_NAME,
                "用户列表.xls");
        request.setAttribute(CommonExcelExportAction.EXCEL_DATAMAP_NAME,
                dataMap);
        request.getRequestDispatcher("CommonExcelExportAction.do").forward(
                request, response);
        return null;
    }

    /**
     * @param pUserAccountService The userAccountService to set.
     */
    public void setUserAccountService(UserAccountService pUserAccountService) {
        this.userAccountService = pUserAccountService;
    }

}
